package cn.example.practice.servlet;


import cn.example.practice.db.ShopCartDao;
import cn.example.practice.model.CartItem;
import cn.example.practice.model.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;

@WebServlet("/shopCartServlet")
public class ShopCartServlet extends HttpServlet {
    private final ShopCartDao shopCartDao = new ShopCartDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("loginUser");
        List<CartItem> cartItems = shopCartDao.getCartItems(user.getId());
        sendSuccess(response, cartItems);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("loginUser");
        String action = request.getParameter("action");
        Long goodsId = Long.parseLong(request.getParameter("goodsId"));
        boolean success;

        switch (action) {
            case "add":
                int quantity = Integer.parseInt(request.getParameter("quantity"));
                success = shopCartDao.addToCart(user.getId(), goodsId, quantity);
                break;
            case "update":
                quantity = Integer.parseInt(request.getParameter("quantity"));
                success = shopCartDao.updateQuantity(user.getId(), goodsId, quantity);
                break;
            case "remove":
                success = shopCartDao.removeFromCart(user.getId(), goodsId);
                break;
            default:
                sendError(response, "无效的操作");
                return;
        }

        if (success) {
            List<CartItem> cartItems = shopCartDao.getCartItems(user.getId());
            sendSuccess(response, cartItems);
        } else {
            sendError(response, "操作失败");
        }
    }

    private void sendSuccess(HttpServletResponse response, List<CartItem> data) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        StringBuilder json = new StringBuilder();
        json.append("{\"success\":true,\"data\":[");

        for (int i = 0; i < data.size(); i++) {
            CartItem item = data.get(i);
            json.append("{")
                    .append("\"id\":").append(item.getId()).append(",")
                    .append("\"goodsId\":").append(item.getGoodsId()).append(",")
                    .append("\"name\":\"").append(escapeJson(item.getName())).append("\",")
                    .append("\"price\":").append(item.getPrice()).append(",")
                    .append("\"quantity\":").append(item.getQuantity())
                    .append("}");

            if (i < data.size() - 1) {
                json.append(",");
            }
        }

        json.append("]}");
        response.getWriter().write(json.toString());
    }

    private void sendError(HttpServletResponse response, String message) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write("{\"success\":false,\"message\":\"" + escapeJson(message) + "\"}");
    }

    private String escapeJson(String input) {
        if (input == null) {
            return "";
        }
        return input.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\b", "\\b")
                .replace("\f", "\\f")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }
}
